<?php
namespace app\admin\controller;

use think\facade\View;
use think\Request;
use think\response\Json;

class CollectResult extends AdminBase
{
    public function initialize()
    {
        parent::initialize();
        $this->m = new \app\admin\model\collect\CollectResult();   //别名：避免与控制名冲突
    }

    public function index()
    {
        return View::fetch("collect/collect_result/index");
    }

    public function tree($page = 1, $limit = 10)
    {
        return $this->m->pageTable($page, $limit);
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if ($this->v && !$this->v->scene('add')->check($data)) {
                return xjson(404, $this->v->getError());
            }
            $result = $this->m->create($data);
            if ($result) {
                return xjson();
            } else {
                return xjson(404, '添加失败！');
            }
        }
        return View::fetch("collect/collect_result/add");
    }

    public function edit($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($this->v && !$this->v->scene('edit')->check($data)) {
                return xjson(404, $this->v->getError());
            }
            $this->m = $this->m->find($id);
            $result = $this->m->save($data);
            if ($result) {
                return xjson();
            } else {
                return xjson(404, '修改失败!');
            }
        } else {
            $data = $this->m->find($id);
            $data->result=json_encode(json_decode($data->result),JSON_UNESCAPED_UNICODE);
            View::assign('data', $data);
            return View::fetch("collect/collect_result/edit");
        }
    }

    public function ajax($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($this->v && !$this->v->scene('ajax')->check($data)) {
                return json(['code' => 404, 'msg' => $this->v->getError(), 'data' => null]);
            }
            $m = $this->m->find($id);
            $m[key($data)] = $m[key($data)] ? 0 : 1;
            $result = $m->save();
            if ($result) {
                return xjson();
            } else {
                return xjson(404, '修改失败！');
            }
        } else {
            return xjson(403, '请求不被允许');
        }
    }

    public function delete($id)
    {
        if (request()->isPost()) {
            $result = $this->m->where('id','in',$id)->delete();
            if ($result) {
                return xjson( '删除成功！');
            } else {
                return xjson(404, '删除失败！');
            }
        }
    }
}